package cqrtplm.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.hustcad.plm.basic.multipartfile.LocalFileMultipartFile;
import com.hustcad.plm.pdm.common.model.vo.search.SearchClassificationVO;
import com.hustcad.plm.pdm.common.service.search.TyplmClassifySearchService;
import com.hustcad.plm.pdm.common.util.CommonUtil;
import com.hustcad.plm.pdm.file.model.dto.BatchUploadDTO;
import com.hustcad.plm.pdm.file.service.TyplmFileHandleService;
import com.hustcad.plm.pdm.flowbusiness.model.entity.FlowObject;
import com.hustcad.plm.pdm.flowbusiness.model.entity.FlowObjectPackageLink;
import com.hustcad.plm.pdm.flowbusiness.model.entity.WorkFlowObjectPackage;
import com.hustcad.plm.pdm.iba.service.TyplmAttributeValueService;
import com.hustcad.plm.pdm.modeling.model.dto.TyplmGeneralOperationDTO;
import com.hustcad.plm.pdm.mpmlink.service.TyplmMpmOperationAdaptationService;
import com.hustcad.plm.pdm.mpmlink.service.TyplmToolingAdaptationService;
import com.hustcad.plm.pdm.partbom.service.view.TyplmViewDefService;
import com.hustcad.plm.pdm.type.service.TyplmTypeService;
import com.hustcad.plm.pdm.workflow.model.entity.WorkFlowContainerView;
import com.hustcad.plm.pdm.workflow.service.TyplmWorkFlowContainerService;
import com.ty.basic.constant.TableTypeConstrant;
import com.ty.basic.entity.IdentifierEntity;
import com.ty.basic.entity.org.UserDO;
import com.ty.basic.entity.type.TypeDO;
import com.ty.basic.entity.view.ViewDefDO;
import com.ty.basic.exception.message.SystemErrorCodeEnum;
import com.ty.basic.session.TyAccountContext;
import com.ty.basic.utils.excel.converter.ExcelToList;
import com.ty.basic.vo.AttributeVO;
import cqrtplm.common.CommonService;
import cqrtplm.constant.RTErrorCodeEnum;
import cqrtplm.constant.RTPlmConstant;
import cqrtplm.dto.*;
import cqrtplm.mapper.RTEngraveMapper;
import cqrtplm.mapper.RTPartMapper;
import cqrtplm.mapper.RTProcessMapper;
import cqrtplm.mapper.RTSubfolderMapper;
import cqrtplm.service.RTProcessRouteService;
import cqrtplm.util.RTFileUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.net.URLEncoder;
import java.util.*;
import java.util.stream.Collectors;

import static com.ty.basic.utils.excel.converter.ExcelToList.getWorkbook;

@Service
@Slf4j
public class RTProcessRouteServiceImpl implements RTProcessRouteService {

    @Resource
    private TyplmMpmOperationAdaptationService typlmMpmOperationAdaptationService;
    @Resource
    private RTProcessMapper rtProcessMapper;
    @Resource
    private CommonService commonService;
    @Value("${rt.tool.export.model.path:templates/exportToolChecklistTemplate.xlsx}")
    private String basicToolModelPath;
    @Resource
    private RTFileUtil rtFileUtil;
    @Resource
    private TyplmFileHandleService typlmFileHandleService;
    @Resource
    private TyplmClassifySearchService typlmClassifySearchService;
    @Resource
    private RTEngraveMapper rtEngraveMapper;
    @Resource
    private RTPartMapper rtPartMapper;
    @Value("${ftp.remote.dir.path}")
    private  String remoteDirPath;
    @Resource
    private TyplmToolingAdaptationService typlmToolingAdaptationService;
    @Resource
    private TyplmWorkFlowContainerService typlmWorkFlowContainerService;
    @Resource
    private RTSubfolderMapper rtSubfolderMapper;
    @Resource
    private TyplmTypeService typlmTypeService;
    @Resource
    private TyplmAttributeValueService typlmAttributeValueService;
    @Resource
    private TyplmViewDefService typlmViewDefService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void importProcess(ImportProcessStepDTO dto) throws Exception {
        MultipartFile file = dto.getFile();
        // 从excel表格中读取图片
        Map<String, File> imageFileMap = new HashMap<>();
        try {
            //读取基础数据
            Map<String, String> fieldMap = ExcelToList.getExcelPropertySettingMapByClass(ImportProcessDTO.class);
            Workbook workbook = getWorkbook(file);
            for (int i = 0; i < workbook.getNumberOfSheets(); i++) {
                Sheet sheet = workbook.getSheetAt(i);
                for (Row row : sheet) {
                    for (Cell cell : row) {
                        cell.setCellType(CellType.STRING);
                    }
                }
            }
            List<ImportProcessDTO> importProcessDTOS = ExcelToList.excelToList(0, 0, workbook, ImportProcessDTO.class,
                                                                               fieldMap);
            List<ImportProcessDTO> filteredList = importProcessDTOS.stream().filter(ImportProcessDTO::isRowEmpty)
                    .collect(Collectors.toList());
            if (CollUtil.isEmpty(filteredList)) {
                throw SystemErrorCodeEnum.EXCEL_READ_EXCEPTION.getException("Excel文件");
            }

            // 计算总步数
            BigDecimal totalCycleTime = filteredList.stream().map(item -> new BigDecimal(item.getCycleTime())).reduce(
                    BigDecimal.ZERO, BigDecimal::add);
            BigDecimal ave = totalCycleTime.divide(new BigDecimal(dto.getPositionNumber()));
            BigDecimal add = ave.add(new BigDecimal(dto.getDeviation()));

            // 初始化
            List<ImportProcessDTO> list = new ArrayList<>();
            List<ProcessDTO> processDTOS = new ArrayList<>();
            BigDecimal processTime = new BigDecimal(BigInteger.ZERO);

            for (ImportProcessDTO importProcessDTO : filteredList) {
                BigDecimal cycleTime = new BigDecimal(importProcessDTO.getCycleTime());
                processTime = processTime.add(cycleTime);
                if (processTime.compareTo(add) <= 0) {
                    list.add(importProcessDTO);
                } else {
                    // 创建当前批次
                    ProcessDTO processDTO = new ProcessDTO("工序", "", String.valueOf(processTime.subtract(cycleTime)),
                                                           dto.getProcessStageId(), list);
                    processDTOS.add(processDTO);
                    // 重置并处理当前元素
                    list = new ArrayList<>();
                    list.add(importProcessDTO);
                    processTime = cycleTime;
                }
            }

            if (CollUtil.isNotEmpty(list)) {
                ProcessDTO processDTO = new ProcessDTO("工序", "", String.valueOf(processTime), dto.getProcessStageId(),
                                                       list);
                processDTOS.add(processDTO);
            }
            if (CollUtil.isEmpty(processDTOS)) {
                return;
            }
            imageFileMap = rtFileUtil.extractImages(file);
            int i = 1;
            UserDO user = TyAccountContext.getUser();
            for (ProcessDTO processDTO : processDTOS) {
                processDTO.setProcessName(processDTO.getProcessName() + i++);
                TyplmGeneralOperationDTO createProcessDTO = l2Dto(processDTO);

                ViewDefDO manufacturing = typlmViewDefService.getViewByName("Design");
                String viewOid = manufacturing.getOid().toString();
                createProcessDTO.getParentObj().put("viewdefoid",viewOid);
                List<String> processOidS = typlmMpmOperationAdaptationService.batchCreateOperation(createProcessDTO);
                List<ImportProcessDTO> stepList = processDTO.getList();
                if (CollUtil.isNotEmpty(processOidS) && CollUtil.isNotEmpty(stepList)) {
                    int gxh = 1;
                    for (ImportProcessDTO step : stepList) {
                        TyplmGeneralOperationDTO createStepDTO = l3Dto(step, processOidS.get(0), gxh++);
                        createStepDTO.getParentObj().put("viewdefoid",viewOid);
                        List<String> stepOisS = typlmMpmOperationAdaptationService.batchCreateOperation(createStepDTO);
                        if (CollUtil.isNotEmpty(stepOisS)) {
                            List<IdentifierEntity> toolEntityList = new ArrayList<>();
                            String StepOid = stepOisS.get(0);
                            //处理工具
                            if (StringUtils.isNotBlank(step.getToolNumber())) {
                                List<String> toolNumbers = splitNumber(step.getToolNumber());
                                toolEntityList.addAll(rtProcessMapper.listTool(toolNumbers));
                            }
                            // 辅料
                            if (StringUtils.isNotBlank(step.getMaterialNumber())) {
                                List<String> materialNumbers = splitNumber(step.getMaterialNumber());
                                toolEntityList.addAll(rtProcessMapper.listMaterial(materialNumbers));
                            }
                            TyplmGeneralOperationDTO createToolsLinkDTO = toolOperationDTO(toolEntityList, StepOid);
                            this.typlmMpmOperationAdaptationService.insertOperationToConsumableLink(createToolsLinkDTO);
                        }
                    }
                    //处理图纸
                    List<String> idS = stepList.stream().map(ImportProcessDTO::getId).collect(Collectors.toList());
                    if (CollUtil.isNotEmpty(imageFileMap)) {
                        uploadProcessDrawing(idS, imageFileMap, processOidS, user);
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw RTErrorCodeEnum.EXCEL_IMPORT_EXCEPTION.getException(e.getMessage());
        } finally {
            Collection<File> values = imageFileMap.values();
            for (File image : values) {
                if (!image.delete()) {
                    // 记录删除失败的日志
                    log.error("Failed to delete file: {}" , image.getAbsolutePath());
                }
            }
        }
    }

    /**
     * 上传工艺附图
     */
    private void uploadProcessDrawing(List<String> idS, Map<String, File> imageFileMap, List<String> processOidS, UserDO user) {
        List<File> files = idS.stream().filter(imageFileMap::containsKey).map(imageFileMap::get).collect(Collectors.toList());
        if (CollUtil.isNotEmpty(files)) {
            List<MultipartFile> imageList = files.stream().map(t -> new LocalFileMultipartFile(t, "application/octet-stream", t.getName(), t.getName())).collect(Collectors.toList());
            BatchUploadDTO batchUploadDTO = new BatchUploadDTO();
            batchUploadDTO.setRoleKey("MPMGYFT");
            batchUploadDTO.setInsertFlag(true);
            batchUploadDTO.setFileList(imageList);
            batchUploadDTO.setOid(processOidS.get(0));
            batchUploadDTO.setUpdatoroid(user.getOid());
            batchUploadDTO.setUpdatorotype(user.getUsertype());
            batchUploadDTO.setOtype("ty.inteplm.mpm.CTyMPMOperation");
            this.typlmFileHandleService.batchUploadFile(batchUploadDTO);
        }
    }


    private static TyplmGeneralOperationDTO toolOperationDTO(List<IdentifierEntity> toolEntityList, String stepOid) {
        TyplmGeneralOperationDTO goDTO = new TyplmGeneralOperationDTO();
        for(IdentifierEntity entity : toolEntityList){
            JSONObject currentObj = new JSONObject();
            currentObj.put("masteredoid",entity.getOid());
            currentObj.put("masteredotype",entity.getOtype());
            goDTO.getCurrentObj().add(currentObj);
        }
        JSONObject parentObj = goDTO.getParentObj();
        parentObj.put("otype", "ty.inteplm.mpm.CTyMPMOperation");
        parentObj.put("oid", stepOid);
        return goDTO;
    }

    private static List<String> splitNumber(String toolNumber) {
        // 使用正则表达式分割中英文分号
        String[] parts = toolNumber.split("[；;]");
        // 处理分割结果：去空白、过滤空值
        return Arrays.stream(parts).map(String::trim).filter(s -> !s.isEmpty()).collect(Collectors.toList());
    }

    private static TyplmGeneralOperationDTO l2Dto(ProcessDTO processDTO) {

        TyplmGeneralOperationDTO goDTO = new TyplmGeneralOperationDTO();
        JSONObject currentObj = new JSONObject();
        currentObj.put("otype", "ty.inteplm.mpm.CTyMPMOperation|processSequence");
        currentObj.put("typeotype", "ty.inteplm.mpm.CTyMPMOperation|processSequence");
        currentObj.put("name", processDTO.getProcessName());
        currentObj.put("ibaList", new ArrayList<>());
        goDTO.getCurrentObj().add(currentObj);
        JSONObject parentObj = goDTO.getParentObj();
        parentObj.put("otype", "ty.inteplm.mpm.CTyMPMOperation");
        parentObj.put("viewdefoid", "");
        parentObj.put("oid", processDTO.getProcessStageOid());
        return goDTO;
    }

    private static TyplmGeneralOperationDTO l3Dto(ImportProcessDTO dto, String oid, int gxh) {
        TyplmGeneralOperationDTO goDTO = new TyplmGeneralOperationDTO();
        JSONObject currentObj = new JSONObject();
        currentObj.put("otype", "ty.inteplm.mpm.CTyMPMOperation|processStep");
        currentObj.put("typeotype", "ty.inteplm.mpm.CTyMPMOperation|processStep");
        currentObj.put("name", dto.getStepName());
        currentObj.put("ibaList", getIbaList(dto, gxh));
        currentObj.put("formattedtextablob", dto.getStepContent());//工序内容
        goDTO.getCurrentObj().add(currentObj);
        JSONObject parentObj = goDTO.getParentObj();
        parentObj.put("otype", "ty.inteplm.mpm.CTyMPMOperation");
        parentObj.put("viewdefoid", "");
        parentObj.put("oid", oid);
        return goDTO;
    }

    private static JSONArray getIbaList(ImportProcessDTO dto,int gxh) {
        JSONArray ibaList = new JSONArray();
        ibaList.add(getIbaJsonObject("gxh", gxh));
        ibaList.add(getIbaJsonObject("partName", dto.getPartName()));
        ibaList.add(getIbaJsonObject("partNumber", dto.getPartNumber()));
        ibaList.add(getIbaJsonObject("partQuantity", dto.getPartQuantity()));
        return ibaList;
    }

    private static JSONObject getIbaJsonObject(String key, Object value) {
        JSONObject iba = new JSONObject();
        iba.put("key", key);
        iba.put("value", value);
        return iba;
    }
    @Override
    public void exportToolsAndEquipment(ExportToolDTO dto, HttpServletResponse response) throws Exception {
        List<String> stageOidList = new ArrayList<>();
        String otype = dto.getOtype();
        if(StringUtils.isEmpty(otype) || StringUtils.isBlank(otype)){
            return;
        }
        if(otype.contains("|")){
            otype = otype.split("\\|")[0];
        }
        if (TableTypeConstrant.TY_MPMPROCESSPLAN_TYPE.equals(otype)) {
            List<String> stageOids = rtProcessMapper.listGx(CollectionUtil.toList(dto.getOid()));
            if (CollUtil.isNotEmpty(stageOids)) {
                stageOidList.addAll(stageOids);
            }
        } else {
            stageOidList.add(dto.getOid());
        }
        if (CollUtil.isEmpty(stageOidList)) {
            throw RTErrorCodeEnum.EXCEL_EXPORT_EXCEPTION.getException("导出工装工具清单失败 : data is null !");
        }
        //根据工艺阶段OID查询下级工序OID
        List<String> gxOidList = rtProcessMapper.listGx(stageOidList);
        //根据工序OID 查询 下级工步 工步关联工具信息
        List<processToolDTO> processToolDTOS = rtProcessMapper.queryStepToolByProcessOid(gxOidList);
        for (int i = 0; i < processToolDTOS.size(); i++) {
            processToolDTO processToolDTO = processToolDTOS.get(i);
            processToolDTO.setNo(String.valueOf(i + 1));
        }

        //导出
        String templateFileName = commonService.getFilePath(basicToolModelPath);
        RTExportFileDTO destFile = commonService.getDestFile(dto.getNumber() + "工装工具清单");
        List<JSONObject> json = rtProcessMapper.getProcessPlanAttributes(dto.getOid());
        Map<String, String> processPlanAttributes = json.stream()
                .collect(Collectors.toMap(
                        obj -> obj.getString("KEY"),
                        obj -> obj.getString("VALUE")
                ));
        exportToExcel(templateFileName, destFile, response, processToolDTOS,processPlanAttributes);
    }
    private void exportToExcel(String templateFileName,RTExportFileDTO dto,HttpServletResponse response, List<processToolDTO> list,Map<String, String> processPlanAttributes) throws Exception {
        File sourceFile = new File(templateFileName);
        File destFile = new File(dto.getFilePath());
        try {
            // 确保目标文件的目录存在
            if (!destFile.getParentFile().exists()) {
                destFile.getParentFile().mkdirs();
            }
            // 使用 FileInputStream 和 FileOutputStream 复制文件
            try (FileInputStream fis = new FileInputStream(sourceFile);
                 FileOutputStream fos = new FileOutputStream(destFile)) {
                byte[] buffer = new byte[1024];
                int length;
                while ((length = fis.read(buffer)) > 0) {
                    fos.write(buffer, 0, length);
                }
            }

            FileInputStream fis = new FileInputStream(destFile);
            Workbook workbook = new XSSFWorkbook(fis);
            Sheet sheet = workbook.getSheetAt(0);

            CellStyle style = workbook.createCellStyle();
            style.setAlignment(HorizontalAlignment.CENTER); // 水平居中
            style.setVerticalAlignment(VerticalAlignment.CENTER); // 垂直居中
            style.setBorderTop(BorderStyle.THIN); // 上边框
            style.setBorderBottom(BorderStyle.THIN); // 下边框
            style.setBorderLeft(BorderStyle.THIN); // 左边框
            style.setBorderRight(BorderStyle.THIN); // 右边框

            Row row2 = sheet.getRow(2);
            createAndSetCell(row2, 1, processPlanAttributes.get("机型集合"), style);
            createAndSetCell(row2, 5, processPlanAttributes.get("开发令"), style);

            int rowNum = 4;
            for (processToolDTO stepDTO : list) {
                Row row = sheet.createRow(rowNum++);
                createAndSetCell(row, 0, StringUtils.defaultIfBlank(stepDTO.getNo(), ""), style); // 序号
                createAndSetCell(row, 1, StringUtils.defaultIfBlank(stepDTO.getProcessCode(), ""), style);
                createAndSetCell(row, 2, StringUtils.defaultIfBlank(stepDTO.getProcessName(), ""), style);
                createAndSetCell(row, 3, StringUtils.defaultIfBlank(stepDTO.getToolName(), ""), style);
                createAndSetCell(row, 4, StringUtils.defaultIfBlank(stepDTO.getToolCode(), ""), style);
                createAndSetCell(row, 5, StringUtils.defaultIfBlank(stepDTO.getToolSpec(), ""), style);
                createAndSetCell(row, 6, StringUtils.defaultIfBlank(stepDTO.getAmount(), ""), style);
            }
            String fileName = dto.getFileName();
            if(!fileName.contains(".xlsx")){
                fileName+=".xlsx";
            }

            String encodeFileName = URLEncoder.encode(fileName, "UTF-8").replace("\\+","20%");
            if(fileName.contains(" ")){
                encodeFileName =encodeFileName.replace("+","%20");
            }
            response.setContentType("application/vnd.ms-excel");
            response.setHeader("Content-Disposition", "attachment;filename=" + encodeFileName);
            OutputStream outputStream = response.getOutputStream();
            workbook.write(outputStream); // 将Workbook对象写入流中
            response.setCharacterEncoding("UTF-8");
            outputStream.close();
            workbook.close();
        }catch (Exception e){
            e.printStackTrace();
            throw new RuntimeException(e);
        }finally {
            destFile.delete();
        }
    }

    private static void createAndSetCell(Row row, int columnIndex, String value, CellStyle style) {
        if ("null".equals(value)) {
            value = "";
        }
        Cell cell = row.createCell(columnIndex);
        cell.setCellValue(value);
        cell.setCellStyle(style);
    }

    @Override
    public List<KeyValueDTO> getDevelopmentOrderList(String keyword) {
        List<BigInteger> partOidList =rtEngraveMapper.selectIbaAttr("ProductSpecification");
        List<List<BigInteger>> partOidListList = CommonUtil.subObjectList(partOidList, 999);
        Map<String, List<AttributeVO>> partIbaMap = new HashMap<>();

        for (List<BigInteger> list : partOidListList) {
            Map<String, List<AttributeVO>> map = typlmAttributeValueService.getIbaAttrValueByOidAndKeys(
                    list,
                    TableTypeConstrant.TY_PART_OTYPE,
                    Collections.singletonList(RTPlmConstant.DEVELOPMENT));
            if(CollUtil.isNotEmpty(map)){
                partIbaMap.putAll(map);
            }
        }
        List<String> devCodeList = new ArrayList<>();
        for (String partOid : partIbaMap.keySet()) {
            List<AttributeVO> attributeVOS = partIbaMap.get(partOid);
            String devCode = "";
            for (AttributeVO attributeVO : attributeVOS) {
                if (RTPlmConstant.DEVELOPMENT.equals(attributeVO.getAttributeEnName())) {
                    devCode = StringUtils.isBlank(attributeVO.getAttributeValuex()) ? attributeVO.getAttributeValue()
                            : attributeVO.getAttributeValuex();
                }
            }
            devCodeList.add(devCode);
        }
        return devCodeList.stream()
                .filter(devCode -> StringUtils.isBlank(keyword) || devCode.contains(keyword))
                .map(devCode -> KeyValueDTO.of(devCode, devCode))
                .collect(Collectors.toList());
    }

    private void getAllClassificationOid(List<SearchClassificationVO> searchClassificationVOS,
                                         List<BigInteger> classificationOidList) {
        for(SearchClassificationVO vo:searchClassificationVOS){
            classificationOidList.add(vo.getOid());
            if(CollUtil.isNotEmpty(vo.getChildrenList())){
                getAllClassificationOid(vo.getChildrenList(),classificationOidList);
            }
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void createTools(String workFlowContainerId) {
        WorkFlowContainerView workFlowContainerView = typlmWorkFlowContainerService.getWorkFlowContainerDetailByPrimaryKey(new BigInteger(workFlowContainerId));
        if (!Objects.isNull(workFlowContainerView) && workFlowContainerView instanceof WorkFlowObjectPackage) {
            WorkFlowObjectPackage workFlowObjectPackage = (WorkFlowObjectPackage) workFlowContainerView;
            List<FlowObject> flowObjectList = workFlowObjectPackage.getFlowObjectList();
            String workFlowName = workFlowObjectPackage.getWorkFlowName();
            if (CollUtil.isEmpty(flowObjectList)) {
                return;
            }
            TyplmGeneralOperationDTO goDTO = new TyplmGeneralOperationDTO();

            JSONObject param = new JSONObject();
            JSONObject parent = new JSONObject();
            if(workFlowName.contains("工具")){
                List<TypeDO> typeDOS = typlmTypeService.queryDefaultDOByInthidList(
                        Collections.singletonList(RTPlmConstant.MPM_TOOL_TYPE));
                BigInteger typeOid = typeDOS.get(0).getOid();
                param.put("otype", RTPlmConstant.MPM_TOOL_TYPE);
                param.put("typeOid", typeOid);
                goDTO.setParam(param);
                parent.put("otype", TableTypeConstrant.TY_SUBFOLDER_OTYPE);
                parent.put("oid", rtSubfolderMapper.selectSubfolderOidByName("工具"));
                goDTO.setParentObj( parent);
                setCurrentObjList(flowObjectList,goDTO);
            }else if(workFlowName.contains("工装")){
                List<TypeDO> typeDOS = typlmTypeService.queryDefaultDOByInthidList(
                        Collections.singletonList(RTPlmConstant.MPM_ACCESSORY_TYPE));
                BigInteger typeOid = typeDOS.get(0).getOid();
                param.put("otype", RTPlmConstant.MPM_ACCESSORY_TYPE);
                param.put("typeOid", typeOid);
                goDTO.setParam(param);
                parent.put("otype", TableTypeConstrant.TY_SUBFOLDER_OTYPE);
                parent.put("oid", rtSubfolderMapper.selectSubfolderOidByName("工装"));
                goDTO.setParentObj( parent);
                setCurrentObjList(flowObjectList,goDTO);
            }else {
                return;
            }
            this.typlmToolingAdaptationService.batchCreateTooling(goDTO);
        }
    }

    private void setCurrentObjList(List<FlowObject> flowObjectList, TyplmGeneralOperationDTO goDTO) {
        List<String> ibaNames = Collections.singletonList("stage");
        List<BigInteger> partOidList = flowObjectList.stream().map(FlowObjectPackageLink::getRefObjectOid).collect(
                Collectors.toList());
        Map<String, List<AttributeVO>> attrValueByOidAndKeys = typlmAttributeValueService.getIbaAttrValueByOidAndKeys(
                partOidList,
                TableTypeConstrant.TY_PART_OTYPE,
                ibaNames);
        List<JSONObject> currentObjList = new ArrayList<>();
        for (FlowObject flowObject : flowObjectList) {
            JSONObject currentObj = new JSONObject();
            currentObj.put("objectnumber", flowObject.getObjectNumber());
            currentObj.put("name", flowObject.getName());
            currentObj.put("typeOid", goDTO.getParam().getString("typeOid"));
            currentObj.put("otype", goDTO.getParam().getString("otype"));
//            currentObj.put("defaultunitkey", "");
            List<AttributeVO> attributeVOS = attrValueByOidAndKeys.get(String.valueOf(flowObject.getRefObjectOid()));
            if(CollUtil.isNotEmpty(attributeVOS)){
                String attributeValue = attributeVOS.get(0).getAttributeValue();
                JSONArray ibaList = new JSONArray();
                JSONObject iba = new JSONObject();
                iba.put("name", "spec");
                iba.put("value", attributeValue);
                ibaList.add(iba);
                currentObj.put("ibaList", ibaList);
            }
            currentObjList.add(currentObj);
        }
        goDTO.setCurrentObj(currentObjList);
    }
}
